package com.yld.car.market;

import java.util.ArrayList;
import java.util.HashMap;

import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import cn.yld.car.adapter.CarTypeAdapter;
import cn.yld.car.db.RecentlyViewedDBHelper;

import com.yld.car.common.ConstantUtils;
import com.yld.car.common.NetworkProgressUtils;
import com.yld.car.domain.BaseColorInfo;
import com.yld.car.domain.Car;
import com.yld.car.domain.FilterCarInfo;
import com.yld.car.domain.SearchDetailCar;

public class FindCarHomePageActivity extends BaseActivity implements
		OnItemClickListener {

	private Button rightButton;
	private Button modelButton;

	private ListView carTypeList;

	private String id;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		// 去掉标题栏
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.car_type);
		initViews();
		Intent i = getIntent();
		mBar = (ProgressBar) findViewById(R.id.progressBar);
		String name = i.getStringExtra("name");
		id = i.getStringExtra("carId");
		id = "1";

		utils = NetworkProgressUtils.getInstance();
		super.onCreate(savedInstanceState);

		carTypeList = (ListView) findViewById(R.id.list1);
		// showButton();

		carTypeList.setOnItemClickListener(this);
		// new CarTypeTask().execute(new String[] { "8", "", "" });

	}

	private ProgressBar mBar;
	private View.OnClickListener filterOnClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {

			Intent intent = new Intent();
			intent.setClass(FindCarHomePageActivity.this,
					FilterTypeActivity.class);
			startActivityForResult(intent, 1);

		}
	};

	private void showButton() {

		Button localButton = (Button) findViewById(R.id.leftButton);
		localButton.setVisibility(View.VISIBLE);

		localButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				finish();

			}
		});
	}

	private NetworkProgressUtils utils;

	private class CarTypeTask extends AsyncTask<String, String, ArrayList<Car>> {

		@Override
		protected ArrayList<Car> doInBackground(String... params) {

			/*
			 * 参数一：keyWords：点击某一个系列的ID或者是在搜索框输入的关键字
			 * 参数二：color：颜色，（数据列表页面右上角筛选按钮中的颜色，默认为空，参数值例如：“红”）
			 * 参数三：type：车辆类型，期货还是现货（数据列表页面右上角筛选按钮中的期现货，默认为空，参数值例如: “期货”
			 * 注意不能传入“美国期货”或者 “美国现货”）
			 * 参数四：port:港口名称，（数据列表页面右上角筛选按钮中的港口，默认为空，参数值例如：“张家港”） 参数五：flag:区别标示
			 * ，（参数值为“1”时：用户是通过点击某一个系列进入这个页面的，参数值为“2”时：通过在搜索框输入关键字进入这个页面的
			 * 注意：此参数要与keyWords相对应） 参数六：nowPage:当前页码，（参数值例如：“1”）
			 * 参数七：pageSize:每页显示条数，（参数值例如：“20”）
			 */

			HashMap<String, String> allParams = new HashMap<String, String>();
			// allParams.put("keyWords", id);
			// allParams.put("color", params[0]);
			// allParams.put("type", params[1]);
			// allParams.put("port", params[2]);
			// allParams.put("flag", "1");
			// allParams.put("nowPage", "1");
			// allParams.put("pageSize", "20");

			allParams.put("classId", params[0]);
			allParams.put("color", params[1]);
			allParams.put("deploy", params[2]);
			allParams.put("port", params[3]);
			allParams.put("nowPage", "1");
			allParams.put("pageSize", "20");
			Object o = utils.getWebservicesByData(
					ConstantUtils.NAME_SPACE,
					ConstantUtils.ALL_METHROD_NAME.get(38),
					ConstantUtils.NAME_SPACE
							+ ConstantUtils.ALL_METHROD_NAME.get(38),
					ConstantUtils.GET_PAGE_DATA_CARS_NEW_URL, allParams);

			// System.out.println(o);
			// System.out.println("=======================");
			ArrayList<Car> all = utils.parseJson(o.toString(), "table",
					NetworkProgressUtils.SEARCH_CAR_TYPE,true);

			// for (Car car : c) {
			//
			// if(car instanceof SearchDetailCar){
			//
			// SearchDetailCar s=(SearchDetailCar)car;
			// System.out.println(s);
			// }
			// }
			// System.out.println(c);
			return all;
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			mBar.setVisibility(View.VISIBLE);
			carTypeList.setVisibility(View.GONE);
		}

		@Override
		protected void onPostExecute(ArrayList<Car> result) {

			super.onPostExecute(result);

			mBar.setVisibility(View.GONE);
			carTypeList.setVisibility(View.VISIBLE);
			if (result != null) {

				CarTypeAdapter adapter = new CarTypeAdapter(result,
						FindCarHomePageActivity.this);
				carTypeList.setAdapter(adapter);
			}
		}

	}

	@Override
	public void onItemClick(AdapterView<?> adapterView, View v, int position,
			long id) {

		Object o = adapterView.getAdapter().getItem(position);

		if (o instanceof SearchDetailCar) {

			final SearchDetailCar s = (SearchDetailCar) o;
			// new Thread(new Runnable() {
			//
			// /**
			// * { "recordcount":"1", --返回的数据条数 "table": [ { "no":"1", --序列号
			// * "id": "1683", --车辆ID "name": "外白内黑棕", --车辆外饰内饰简称，即这辆车的标题
			// * "classid": "111", --系列ID "press": "115", --价格（单位W） "qhtime":
			// * "2014-04-30", --到港时间（期货才有时间，现货没有时间即为空） "vin": "", --就是车架号
			// * "xppz": "运动包¤扩展真皮内饰¤红卡钳", --选配配置 "companyname": "",
			// * --这辆车所属经销商公司名称 "adddate": "2014-04-11 18:19:33", --这辆车的录入时间
			// * "pinpainame": "玛莎拉蒂", --此车品牌名称 "xiliename": "GHIBLI S Q4",
			// * --此车系列名称 "gangkouname": "张家港", --这辆车所属经销商公司所在港口 "xhorqh":
			// * "期货" --期货还是现货 } …… ] }
			// */
			// @Override
			// public void run() {
			// SQLiteDatabase sqLiteDatabase = mApp.getmDbHelper()
			// .getWritableDatabase();
			// ContentValues values = new ContentValues();
			// values.put(RecentlyViewedDBHelper.ID, s.getId());
			// values.put(RecentlyViewedDBHelper.NO, s.getNo());
			// values.put(RecentlyViewedDBHelper.NAME, s.getName());
			// values.put(RecentlyViewedDBHelper.CLASS_ID, s.getClassid());
			// values.put(RecentlyViewedDBHelper.PRESS, s.getPress());
			// values.put(RecentlyViewedDBHelper.QHTIME, s.getQhtime());
			// values.put(RecentlyViewedDBHelper.ADD_DATE, s.getAdddate());
			// values.put(RecentlyViewedDBHelper.XPPZ, s.getXppz());
			// values.put(RecentlyViewedDBHelper.COMPANY_NAME,
			// s.getCompanyname());
			// values.put(RecentlyViewedDBHelper.PIN_PAI_NAME,
			// s.getPinpainame());
			// values.put(RecentlyViewedDBHelper.XI_LIE_NAME,
			// s.getXiliename());
			// values.put(RecentlyViewedDBHelper.GANG_KOU_NAME,
			// s.getGangkouname());
			// values.put(RecentlyViewedDBHelper.XHORQH, s.getXhorgh());
			// long rowId = sqLiteDatabase.insert(
			// RecentlyViewedDBHelper.RECENT_VIEW_TABLE, null,
			// values);
			// if (rowId > 0) {
			// System.out.println("insert------>插入成功。");
			// } else {
			//
			// System.out.println("insert------>插入失败。");
			// }
			//
			// }
			// }).start();

			String cId = s.getId();
			Intent intent = new Intent();
			intent.putExtra("cId", cId);
			intent.putExtra("carName", s.getPinpainame());
			System.out.println("carType===="+s.getXhorgh());
			intent.putExtra("carType", s.getXhorgh());// 类型
			intent.putExtra("carSeries", s.getXiliename());
			// 添加经销商dealerid字段
			intent.putExtra("dealerid", s.getDealerid());
			intent.setClass(this, CarDetailInfoActivity.class);
			startActivity(intent);
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);

		if (1 == requestCode && RESULT_OK == resultCode) {

			FilterCarInfo f = (FilterCarInfo) data
					.getSerializableExtra("filter");

			// System.out.println(s);
			new CarTypeTask().execute(new String[] { f.color, f.type, f.port });
		}
	}

	private void initViews() {

		final View v1 = findViewById(R.id.type);

		View v2 = findViewById(R.id.color);

		View v3 = findViewById(R.id.config);
		View v4 = findViewById(R.id.port);
		Button btn1 = (Button) v1.findViewById(R.id.itemContent);
		btn1.setOnClickListener(btn1Listener);
		btn1.setText("类型");
		Button btn2 = (Button) v2.findViewById(R.id.itemContent);
		btn2.setText("颜色");
		btn2.setOnClickListener(btn2Listener);
		Button btn3 = (Button) v3.findViewById(R.id.itemContent);
		btn3.setText("配置");
		btn3.setOnClickListener(btn3Listener);
		Button btn4 = (Button) v4.findViewById(R.id.itemContent);
		btn4.setText("港口");
		btn4.setOnClickListener(btn4Listener);

	}

	View.OnClickListener btn1Listener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {

			Intent intent = new Intent();
			intent.setClass(FindCarHomePageActivity.this,
					FindFilterCarTypeActivity.class);
			startActivity(intent);

		}
	};
	View.OnClickListener btn2Listener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub

			// System.out.println("onClick===2");
			Intent intent = new Intent();
			intent.setClass(FindCarHomePageActivity.this,
					FindCarColorActivity.class);
			String type = mApp.getClassId();
			if (type == null) {
				type = "8";

			}
			intent.putExtra("cId", type);
			startActivity(intent);
		}
	};
	View.OnClickListener btn3Listener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {

			// System.out.println("onClick===3");

			Intent intent = new Intent();
			intent.setClass(FindCarHomePageActivity.this,
					FindCarFilterConfigurationActivity.class);
			String type = mApp.getClassId();
			if (type == null) {
				type = "8";
			}
			intent.putExtra("cId", type);
			startActivity(intent);

		}
	};
	View.OnClickListener btn4Listener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {

			// System.out.println("onClick===4");
			Intent intent = new Intent();
			intent.setClass(FindCarHomePageActivity.this,
					SelectorPortActivity.class);
			intent.putExtra("flag", true);
			startActivity(intent);

		}
	};

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		String classId = mApp.getClassId();
		String color = mApp.getFilterColorValue();
		String configuration = mApp.getFilterConfigurationValue();
		String port = mApp.getmPortInfo();
		if (classId == null) {
			classId = "8";
		}

		if (color == null) {
			color = "";
		}

		// System.out.println("onResume==>" + color);
		if (configuration == null) {
			configuration = "";
		}

		if (port == null) {
			port = "";
		}
		new CarTypeTask().execute(new String[] { classId, color, configuration,
				port });

	}

	@Override
	public void finish() {
		// TODO Auto-generated method stub
		super.finish();
		mApp.setFilterColorValue(null);
		mApp.setClassId(null);
		mApp.setFilterConfigurationValue(null);
	}
}
